package com.tbl.modules.wms2.controller.insidewarehouse;

import cn.hutool.core.date.DateUtil;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.dao.baseinfo.FactoryAreaDAO;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms2.common.RuleCode;
import com.tbl.modules.wms2.dao.baseinfo.BaseDataDao;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderDAO;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderLineDAO;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderEntity;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderLineEntity;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.insidewarehouse.transferorder.TransferOrderLineService;
import com.tbl.modules.wms2.service.insidewarehouse.transferorder.TransferOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 移库调拨上下架
 */
@Controller()
@RequestMapping("/ycl/insidewarehouse/transferInOut")
public class TransferInOutController extends AbstractController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private TransferOrderService transferOrderService;
    @Resource
    private TransferOrderDAO transferOrderDAO;
    @Resource
    private TransferOrderLineDAO transferOrderLineDAO;
    @Autowired
    private TransferOrderLineService transferOrderLineService;
    @Resource
    private FactoryAreaDAO factoryAreaDAO;
    @Resource
    private WarehouseDAO warehouseDAO;
    @Resource
    private CountService countService;
    @Resource
    private BaseDataDao baseDataDao;

    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional
    public Map<String, Object> save(@RequestBody TransferOrderEntity transferEntity) {
        if(transferEntity==null || transferEntity.getLine()==null || transferEntity.getLine().isEmpty()){
            return null;
        }
        List<TransferOrderLineEntity> lines = transferEntity.getLine();

        if(transferEntity.getTranType()==null||transferEntity.getTranType().equals("1")){
            String tranCode = countService.getNextCount("YWDH");
            transferEntity.setTranCode(tranCode);
        }else if (transferEntity.getTranType().equals("3"))
        {
            String tranCode = countService.getNextCount("DBDH");
            transferEntity.setTranCode(tranCode);
        }
        String id = new String();
        if(StringUtils.isEmpty(transferEntity.getId())){
            id = String.valueOf(transferOrderDAO.getSequence());
            transferEntity.setId(id);
        }else{
            id = transferEntity.getId();
        }

        List<Map<String,Object>> fromList = baseDataDao.getAreaList(Integer.parseInt(transferEntity.getFromAreaCode()));
        List<Map<String,Object>> toList = null;
        String fromArea = String.valueOf(fromList.get(0).get("TEXT"));
        String toArea = new String();
        if(transferEntity.getToAreaCode().isEmpty()){
            toArea = fromArea;
        }else{
            toList = baseDataDao.getAreaList(Integer.parseInt(transferEntity.getToAreaCode()));
            toArea = String.valueOf(toList.get(0).get("TEXT"));
        }

        transferEntity.setFromArea(fromArea);
        transferEntity.setToArea(toArea);

        Map<String,Object> fromMap = new HashMap<>();
        fromMap.put("entityId",fromList.get(0).get("ID"));
        fromMap.put("storeCode",String.valueOf(transferEntity.getFromStoreCode()));

        List<Map<String,Object>> fromStoreList = baseDataDao.getStores(fromMap);
        String fromStore = String.valueOf(fromStoreList.get(0).get("TEXT"));

        Map<String,Object> toMap = new HashMap<>();
        toMap.put("entityId",toList==null?fromList.get(0).get("ID"):toList.get(0).get("ID"));
        toMap.put("storeCode",String.valueOf(transferEntity.getToStoreCode()));

        List<Map<String,Object>> toStoreList = baseDataDao.getStores(toMap);
        String toStore = String.valueOf(toStoreList.get(0).get("TEXT"));


        transferEntity.setFromStore(fromStore);
        transferEntity.setToStore(toStore);

        Map resultMap = new HashMap(2);
        //保存头表信息
        try {
            int iHead = transferOrderDAO.insert(transferEntity);

            //保存子表信息
            List<TransferOrderLineEntity> transferOrderLineEntityList = new ArrayList<>(lines.size());
            for (int i = 0; i < lines.size(); i++) {
                TransferOrderLineEntity line = lines.get(i);
                line.setTranId(id);
                line.setUpdateTime(DateUtil.parseDateTime(DateUtil.now()));
                transferOrderLineEntityList.add(line);
            }
            boolean result = (iHead == 1 && transferOrderLineService.saveBatch(transferOrderLineEntityList));

            resultMap.put("result", result);
            resultMap.put("msg", result ? "操作成功！" : "操作失败！");

        }catch (Exception e){
            e.printStackTrace();
        }
        return resultMap;
    }


    @PostMapping(value = "/edit")
    @ResponseBody
    @Transactional
    public Map<String, Object> edit(@RequestBody TransferOrderEntity transferEntity) {
        if(transferEntity==null || StringUtils.isEmpty(transferEntity.getLineId())){
            return null;
        }
        Map resultMap = new HashMap();
        //删除行表数据
        String lineId = transferEntity.getLineId();
        Map<String,Object> map = new HashMap<>();
        map.put("LINE_ID",lineId);
        List<TransferOrderLineEntity> list = transferOrderLineService.getTransferOrderLines(map);

        for(int i=0;i<list.size();i++){
            transferOrderService.delete(list.get(i).getLineId());
        }

        resultMap = this.save(transferEntity);

        return resultMap;

    }





    /**
     * 删除
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/deleteByLineIds")
    @ResponseBody
    @Transactional
    public Map<String, Object> delete(String lineIds) {
        Map<String, Object> map = new HashMap<>(2);
        try {
            String[] aLineIds = lineIds.split(",");
            boolean bh = true;
            //根据行lineId获取tranId,并通过tranId查询满足条件的行表list,如果list大小为1，说明同时要删除头表信息
            for (int i = 0; i < aLineIds.length; i++) {
                TransferOrderLineEntity lineEntity = transferOrderLineService.findById(aLineIds[i]);
                String tranId = lineEntity.getTranId();
                Map<String, Object> findMap = new HashMap<>();
                findMap.put("TRAN_ID", tranId);
                List<TransferOrderLineEntity> lineList = transferOrderLineService.getTransferOrderLines(findMap);
                int bLine = 0;
                if (lineList.size() == 1) {
                    bLine = transferOrderLineDAO.deleteById(aLineIds[i]);
                    bh = transferOrderService.delete(tranId);
                } else {
                    bLine = transferOrderLineDAO.deleteById(aLineIds[i]);
                }

                if (bLine < 1 && bh) {
                    map.put("result", false);
                    map.put("msg", "操作失败！");
                    return map;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("result", true);
        map.put("msg", "操作成功！");
        return map;
    }


    /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/list");
        return mv;
    }


    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(TransferOrderEntity transferOrderEntity) {
        Map<String, Object> paramsMap = getAllParameter();
        //List<TransferOrderEntity> list = transferOrderService.getPageList(paramsMap);

        Map<String, Object> map = new HashMap<>(4);
        return map;
    }

    /**
     * 弹出到明细页面
     *
     * @param tranId 主表主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toDetailList")
    @ResponseBody
    public ModelAndView toDetailList(Long tranId) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/operation/transfer/tran_store_detail");
        mv.addObject("tranId", tranId);
        return mv;
    }

    /**
     * 弹出到新增/编辑页面
     * @return
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public ModelAndView toAdd() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/insidewarehouse/transferorder/edit");

        return mv;
    }

    @RequestMapping(value = "/getTransferOrderById")
    @ResponseBody
    public Map<String,Object> getTransferOrderById(String tranId) {
        TransferOrderEntity transferOrderEntity = transferOrderService.findById(tranId);
        Map<String, Object> map = new HashMap<>(3);
        map.put("msg", "success");
        map.put("result", true);
        map.put("data", transferOrderEntity);
        return map;
    }


}
